package com.easy.leetcode.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @ClassName PostorderTraversal
 * @Description 145. 二叉树的后序遍历
 * @Author zheng
 * @Date 2021/9/6 17:04
 * @Version 1.0
 **/
public class PostorderTraversal145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        res.addAll(postorderTraversal(root.left));
        res.addAll(postorderTraversal(root.right));
        res.add(root.val);
        return res;
    }

    public List<Integer> postorderTraversal1(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null) {
            if (root.left != null) {
                stack.push(root);
                root = root.left;
            } else if (root.right != null) {
                stack.push(root);
                root = root.right;
            } else {
                TreeNode pre = root;
                res.add(root.val);
                root = stack.isEmpty() ? null : stack.pop();
                if (root != null) {
                    if (pre == root.left) {
                        root.left = null;
                    } else {
                        root.right = null;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(-1);
        TreeNode tmp = treeNode;
        for (int i = 0; i < 10; i++) {
            tmp.left = new TreeNode(i);
            i++;
            tmp.right = new TreeNode(i);
            tmp = tmp.left;
        }
        System.out.println(treeNode);
    }
}
